#include "graphicsSceneGrid.h"
#include <QPainter>
#include <QDebug>

GraphicsSceneGrid::GraphicsSceneGrid(QObject *parent)
  : QGraphicsScene(parent),
    mGridSize(0),
    mGridPen(Qt::lightGray)
{
}

void GraphicsSceneGrid::setGridSize(unsigned int size)
{
  mGridSize = size;
}

unsigned int GraphicsSceneGrid::gridSize() const
{
  return mGridSize;
}

void GraphicsSceneGrid::setGridColor(const QColor &color)
{
  mGridPen = QPen(color);
  update();
}

QColor GraphicsSceneGrid::gridColor() const
{
  return mGridPen.color();
}

void GraphicsSceneGrid::drawBackground(QPainter *painter, const QRectF &rect)
{
  painter->fillRect(rect, Qt::black);
  if (mGridSize)
  {
    painter->setPen(mGridPen);

    //horizontal lines
    unsigned int top(static_cast<unsigned int>(rect.top()/mGridSize)*mGridSize+mGridSize);
    for(; top < rect.bottom(); top+=mGridSize)
    {
      painter->drawLine(rect.left(), top, rect.right(), top);
    }

    //vertical lines
    unsigned int left(static_cast<unsigned int>(rect.left()/mGridSize)*mGridSize+mGridSize);
    for(; left < rect.right(); left+=mGridSize)
    {
      painter->drawLine(left, rect.top(), left, rect.bottom());
    }
  }
}
